package handler

import (
	"core-master/cache"
	"core-master/moder"
	"encoding/json"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	GoodsPrice, _ := strconv.Atoi(c.PostForm("GoodsPrice"))
	GoodsName := c.PostForm("GoodsName")
	goods := moder.Goods{
		GoodsPrice: GoodsPrice,
		GoodsName:  GoodsName,
	}

	err := moder.DB.Create(&goods).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "失败",
			"code": 500,
		})
		return
	}

	redis_key := "redis_article" + strconv.Itoa(int(goods.ID))
	var article moder.Goods
	jsonData, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var data []moder.Goods
	redis_key := "redis_list" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		moder.DB.Offset(offset).Limit(size).Order("id asc").Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, result, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &data)
	}

	var total int64
	moder.DB.Model(&moder.Goods{}).Count(&total)
	c.JSON(200, gin.H{
		"mas":   "成功",
		"code":  200,
		"data":  data,
		"total": total,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var data moder.Goods
	redis_key := "redis_detail" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		moder.DB.Where("id=?", id).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, result, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &data)
	}

	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": data,
	})
	return
}
